package com.lp.security.schedule;

import com.lp.biz.member.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * @program: backend
 * @description: id回归定时任务
 * @author: Ke.Song
 * @since: 2024-03-31 0:08:51
 */
@Slf4j
@Component
public class RegressionId {

    @Autowired
    private UserMapper userMapper;

//    @Scheduled(cron = "0 0 1 * * ?")
    public void regression() {
        log.info("开始回归id");
        for (String table : userMapper.getTables()) {
            Set<String> columns = userMapper.getColumns(table);
            if (!columns.contains("id")) {
                continue;
            }
            deletionId(table);
        }
        log.info("id回归结束");
    }

    public void deletionId(String table) {
        Integer id;
        boolean change = false;
        log.info("开始处理{}表", table);
        try {
            do {
                id = userMapper.getDeletionId(table);
                if (id != null) {
                    userMapper.regressionId(table, id);
                    change = true;
                }
            } while (id != null);
            if (change) {
                userMapper.setAutoIncrement(table);
            }
        } catch (Exception e) {
            log.error("处理[{}]表出现错误，错误信息：{}", table, e.getMessage());
        }
    }
}